package net.tribal.comic.controllers

import net.tribal.comic.entities.Page
import net.tribal.comic.entities.AlterPage
import net.tribal.comic.entities.Comic
import net.tribal.comic.entities.Comment
import net.tribal.comic.entities.User


class PageController {
	def pageService
	
	
	/**
     *  Les accions 'delete', 'save' i 'update' nom�s accepten peticions POST
     */
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
                             
                             
	/**
	 * Acci� per defecte
	 */
    def index = { redirect(action: "list", params: params) }

	
    /**
	 * Commuta entre entre el modes de visionat "Coverflow" i "Llistat"
	 */
	def changeView = {
		session['pageViewMode'] = (session['pageViewMode'] == 'list') ? "flow" : "list"
		redirect(controller:"page", action: "list", params: params)
	}
	
	
	/**
    * Mostra les p�gines d'un comic
    * 
    * La cerca podr� ser filtrada per t�tol segons el valor del camp 'searchAjax'
    * 
    * return GSP
    *  render - /page/listContent
    *  render - /page/list
    */
    def list = {
		params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
		
		params.sort = "numberPage"
		params.order = "asc"
		
		def list = pageService.getActivePages(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.searchAjax, params.fromId)

		def title = Comic.get(params.fromId.toLong())?.title 
		
		if(params.searchAjaxAction != null){
	        //	La cerca es as�ncrona
			render(template:"/page/listContent", model:	[pageInstanceList:list['data'], pageInstanceTotal:list['count'], fromId:params.fromId, 'title':title])
			return
		} 
		
        // La cerca es s�ncrona
		render(view:"/page/list", model:[pageInstanceList: list['data'], pageInstanceTotal: list['count'], fromId:params.fromId, title:title])
        return
    }
	

	/**
	 * Mostra la pantalla per crear una p�gina
	 * 
	 * return GSP
     *  render - /page/create
	 */
    def create = {
        def pageInstance = new Page()
        pageInstance.properties = params
		
		if(params.id) {	
			// si existeix, venim de veure el comic, sino es una accio directe
			pageInstance.comic = Comic.get(params.id.toLong())
		}
        
        render(view:"/page/create", model:[pageInstance: pageInstance, comic:pageInstance.comic])
        return 
    }

	
	/**
     * Desa un p�gina
     * 
     * return GSP
     *  redirect /page/list
     *  render - /page/create
     */
    def save = {
		def pageInstance = new Page(params)
		pageInstance.createdBy = session['user']
		
		if(params.customNumberPage.isNumber()){
			if(params.customNumberPage in pageInstance.getSuggestedPages() || params.customNumberPage.toLong() > pageInstance.comic.getMaxNumberPage()){
				pageInstance.numberPage = params.customNumberPage.toLong()
			}else{
				pageInstance.errors.rejectValue('numberPage', 'page.invalid.numberPage')
			}
		}else{
			if ( !(params.suggestedNumberPage.isNumber()) ) {
				def results = Page.withCriteria {
					comic{
						eq("id", params.comic.id.toLong())
					}
					order('numberPage', 'desc')
					maxResults(1)
				}
				if ( results ) {
					pageInstance.numberPage = results[0]? results[0].numberPage + 1: 1
				} else {
					pageInstance.numberPage = 1
				}
			}else{
				pageInstance.numberPage = params.suggestedNumberPage.toLong()
			}
		}
		
        pageService.add( pageInstance, request.getFile('file') )
		
        if (!pageInstance.hasErrors() ) {
            flash.message = "flash.page.created"
			redirect(controller:"comic", action:"show", id:pageInstance.comic.id)
            return
        }
        
        render(view:"/page/create", model:[pageInstance: pageInstance, comic:pageInstance.comic])
        return
    }

	/**
     * Mostra una p�gina
     * 
     * retun
     *  redirect - /page/list
     *  render - /page/show
     */
    def show = {
        def pageInstance = Page.get(params.id)
        
        if (!pageInstance) {
            flash.message = "flash.page.not.found"
            flash.args = [params.id]
            redirect(controller:"page", action:"list")
            return
        }
        
        def userSession = User.get(session.user?.ident())
    	def yourOldRate = pageService.getRateFromPageAndUser ( pageInstance, userSession )
    	
        render(view:"/page/show", model:[pageInstance: pageInstance, 'fromId':pageInstance.comic.id, yourRate:yourOldRate])
	    return
    }

	
	/**
     * M�tode que mostra les dades personals d'un usuari
     * 
     * retun
     * 	redirect - /page/list
     *  render - /page/editProfile
     */
    def editProfile = {
        def pageInstance = Page.get(params.id)
        
        if (!pageInstance) {
            flash.message = "flash.page.not.found"
            flash.args = [params.id]
            redirect(controller:"page", action:"list")
            return
        }
        
		render (view:"/page/editProfile", model:[pageInstance: pageInstance] )
		return
    }
	
	
	/**
     * M�tode que mostra la pantalla per canviar l'imatge de la p�gina
     * 
     * retun
     * 	redirect - /page/list
     *  render - /page/editProfile
     */
    def editFile = {
        def pageInstance = Page.get(params.id)
        
        if (!pageInstance) {
            flash.message = "flash.page.not.found"
            flash.args = [params.id]
            redirect(controller:"page", action:"list")
            return
        }
        
		render (view:"/page/editFile", model:[pageInstance: pageInstance])
		return
    }

	def updateProfile = {
		
	}
	
	def updateFile = {
		
	}
	

    def delete = {
		def pageInstance = pageService.delete( Page.get(params.id) )

		if (!pageInstance) {
			flash.message = "flash.page.not.found"
			flash.args = [params.id]
			redirect(action: "list", params:['fromId':params.fromId])
		}		
		
		if (!pageInstance.hasErrors()) {
            flash.message = "flash.page.deleted"
            flash.args = [params.id]
            redirect(action: "list", params:['fromId':params.fromId])
        } else {
            flash.message = "flash.page.not.deleted"
            flash.args = [params.id]
            redirect(action:"show", params:['fromId':params.fromId])
        }
    }

	
	
	def enable = {
		def instance = Page.get(params.id)
		if ( !instance ) {
			flash.message = "flash.page.not.found"
			flash.args = [params.id]
			redirect(controller:"page", action:"list")
			return
		}
		
		instance.disabled = true
		instance.moderationRequest = false
		def result = pageService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.page.enabled"
			flash.args = [params.id]
            redirect(controller:"page", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"page", action:"show", id:instance.id)
		return
    }
	
	
	def disable = {
		def instance = Page.get(params.id)
		if ( !instance ) {
			flash.message = "flash.page.not.found"
			flash.args = [params.id]
			redirect(controller:"page", action:"list")
			return
		}
		
		instance.disabled = true
		instance.moderationRequest = false
		def result = pageService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.page.enabled"
			flash.args = [params.id]
            redirect(controller:"page", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"page", action:"show", id:instance.id)
		return
    }
	
	
	def moderationRequest = {
		def instance = Page.get(params.id)
		
		if(!instance){
			flash.message = "comic.not.found"
			flash.args = "${params.id}"
			redirect(controller:"comic", action:"list")
		}

		instance.moderationRequest = true
		instance.save()
		
		if(instance.hasErrors()){
			instance.errors.rejectValue('','error.page.moderation.request')
		} else{
			flash.message = "flash.page.moderation.request"
			flash.args = [params.id]			
		}

		render(view:"/page/show", model:[pageInstance:instance])
	}
	
	
	def comments = {
		params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
        
        def list = pageService.getPageComments(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.commentToId)
	    
        render(template:"/comment/list", model:[commentInstanceList: list['data'], commentInstanceTotal:list['count'], commentToName:'page', commentToId:params.commentToId])
        return
    }
	
	def addComment = {
		def comment = new Comment(params)
		comment.createdBy = session['user']
		                            
		//	Si t� errors, mostrem la pantalla de creaci� d'un comentari.
        if (comment.hasErrors() ) {
    		render(template:"/comment/create", model:[commentInstance:comment, commentToName:params.commentToName, commentToId:params.commentToId])
    		return
        }
        
        def page = Page.get(params.commentToId.toLong())
		page.addToComments(comment)
        
        flash.message = "flash.comment.saved"
        redirect(controller:"page", action:"comments", params:[commentToId:params.commentToId])
        return
	}
	
	/**
	 * Afegeix un vot a un usuari
	 * Si es la primera vegada que un usuari vota a un usuari en concret, afegeix un vot
	 * si no, actualiza el vot
	 * 
	 * retun
	 *  render - /rate/rate
	 */
	def rate = {
		def page = Page.get(params.id)
		def userSession = User.get(session.user.ident())
		
		if(pageService.ratePage(params.rating, page, userSession)){
			//	Es puntua correctament
			render(template: "/rate/rateCustom", model:[instance: page, from:'page', yourRate:params.rating])
			return
		}else{
			//	Error al puntuar
			page.errors.rejectValue("", "rate.fault")	
			render(template: "/rate/rateCustom", model:[instance: page, from:'page', yourRate:params.rating])
			return
		}
	}
	
	def bestPage = {
		def bestAlterPage = AlterPage.createCriteria().list{
            page{
				eq("id", params.id.toLong())
			}
		}.max{it.rate}
		
		
		if(!bestAlterPage) {
			redirect(controller:"page", action:"show", params:params)
			return
		}
		
		redirect(controller:"alterPage", action:"show", id:bestAlterPage.id)
		return

	}
}